﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using FlotasDesktop;
using System.Security.Cryptography;

namespace GestorDeFlotasDesktop.AbmUsuario
{
    public partial class ModificarUsuario : Form
    {
        int id;
        String conexion;
        String nombre;
        String password;
        Boolean habilitiado;
        int rol;

        public ModificarUsuario()
        {
            InitializeComponent();
            Utils utils = new Utils();
            conexion = utils.cargarProperties();
            
        }

        internal void mostrateConCampos(String id, String nombre, String password, Boolean habilitiado)
        {
            using (SqlConnection connection = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command = new SqlCommand())
                    {
                        this.id = Convert.ToInt32(id);
                        userTextBox.Text = nombre;
                        habilitadoCheckBox.Checked = habilitiado;
                        cargarComboRolesAsignados();
                        cargarComboRolesGenerales();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            this.Show();

        }

        private void cargarComboRolesAsignados()
        {
            using (SqlConnection connection = new SqlConnection(conexion))
            {
                try
                {
                    
                    string sentSql = "select * from tequilaso.rol where id in (select id_rol from tequilaso.usuario_rol where id_usuario = " + id + " and habilitado = 1)";
                    SqlConnection sqlConn = new SqlConnection(conexion);
                    sqlConn.Open();
                    DataTable objDataTable = new DataTable();
                    SqlDataAdapter dataAdap = new SqlDataAdapter(sentSql, sqlConn);
                    int asda = dataAdap.Fill(objDataTable);

                    rolesAsignadosList.DataSource = (objDataTable);
                    rolesAsignadosList.DisplayMember = "Nombre";
                    rolesAsignadosList.ValueMember = "Id";
                    connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error en la tabla Funcionalidad");
                }
            }
        }

        private void cargarComboRolesGenerales()
        {
            using (SqlConnection connection = new SqlConnection(conexion))
            {
                try
                {

                    string sentSql = "select * from tequilaso.rol where (id not in (select id_rol from tequilaso.usuario_rol where id_usuario = " + id + " and habilitado = 1)) and habilitado = 1";
                    SqlConnection sqlConn = new SqlConnection(conexion);
                    sqlConn.Open();
                    DataTable objDataTable = new DataTable();
                    SqlDataAdapter dataAdap = new SqlDataAdapter(sentSql, sqlConn);
                    int asda = dataAdap.Fill(objDataTable);

                    rolesGeneralesList.DataSource = (objDataTable);
                    rolesGeneralesList.DisplayMember = "Nombre";
                    rolesGeneralesList.ValueMember = "Id";
                    connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error en la tabla Funcionalidad");
                }
            }
        }

        private void Alta_Click(object sender, EventArgs e)
        {
            using (SqlConnection connection = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command = new SqlCommand())
                    {
                        if (passTextBoxVieja.Text.Length > 0)
                        {
                            string sql = "select * from TEQUILASO.Usuario where Nombre = '" + this.userTextBox.Text + "'";
                            connection.Open();
                            command.Connection = connection;
                            command.CommandText = sql;
                            command.CommandType = CommandType.Text;

                            SqlDataReader reader = command.ExecuteReader();
                            if (reader.HasRows)
                            {
                                reader.Read();

                                if (this.validarContraseña(this.passTextBoxVieja.Text, (string)reader["Password"]))
                                {

                                    connection.Close();

                                    this.realizarModificacion();
                                    MessageBox.Show("Modificacion realizada con exito");
                                    this.Close();

                                }
                                else
                                {
                                    MessageBox.Show("Error en la Password antigua, intentelo de nuevo");
                                }
                            }
                        }
                        else
                        {

                            this.realizarModificacionSinPassNueva();
                            MessageBox.Show("Modificacion realizada con exito");
                            this.Close();
                        
                        }

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void realizarModificacionSinPassNueva()
        {
            using (SqlConnection connection1 = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command1 = new SqlCommand())
                    {
                        connection1.Open();
                        command1.Connection = connection1;
                        command1.CommandType = System.Data.CommandType.StoredProcedure;
                        command1.CommandText = "TEQUILASO.sp_modificarUsuarioSinPassNueva";
                        command1.Parameters.AddWithValue("@Id", this.id);
                        command1.Parameters.AddWithValue("@Nombre", userTextBox.Text);
                        command1.Parameters.AddWithValue("@Habilitado", habilitadoCheckBox.Checked);
                        command1.ExecuteReader();
                        connection1.Close();

                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void realizarModificacion()
        {
            using (SqlConnection connection1 = new SqlConnection(conexion))
            {
                try
                {
                    using (SqlCommand command1 = new SqlCommand())
                    {
                        connection1.Open();
                        command1.Connection = connection1;
                        command1.CommandType = System.Data.CommandType.StoredProcedure;
                        command1.CommandText = "TEQUILASO.sp_modificarUsuario";
                        command1.Parameters.AddWithValue("@Id", this.id);
                        command1.Parameters.AddWithValue("@Nombre", userTextBox.Text);
                        command1.Parameters.AddWithValue("@Password", crearContrasenia(passTextBoxNueva.Text));
                        command1.Parameters.AddWithValue("@Habilitado", habilitadoCheckBox.Checked);
                        command1.ExecuteReader();
                        connection1.Close();
                        
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public bool validarContraseña(string cadena, string hash)
        {
            SHA256 sha256 = new SHA256Managed();
            byte[] inputBytes = Encoding.UTF8.GetBytes(cadena);
            byte[] hashedBytes = sha256.ComputeHash(inputBytes);
            StringBuilder hashedString = new StringBuilder();
            string cadenaHash;

            for (int i = 0; i < hashedBytes.Length; i++)
                hashedString.Append(hashedBytes[i].ToString("x2").ToLower());

            cadenaHash = hashedString.ToString();

            for (int i = 0; i < cadenaHash.Length; i++)
            {
                if (!(cadenaHash[i].Equals(hash[i])))
                    return false;
            }

            return true;
        }

        private String crearContrasenia(String contra)
        {
            SHA256 sha256 = new SHA256Managed();
            byte[] inputBytes = Encoding.UTF8.GetBytes(contra);
            byte[] hashedBytes = sha256.ComputeHash(inputBytes);
            StringBuilder hashedString = new StringBuilder();
            string cadenaHash;

            for (int i = 0; i < hashedBytes.Length; i++)
                hashedString.Append(hashedBytes[i].ToString("x2").ToLower());

            cadenaHash = hashedString.ToString();

            return cadenaHash;
        }

        private void ModificarUsuario_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Agregar rol
            if (rolesGeneralesList.Text.Length > 0)
            {
                using (SqlConnection connection = new SqlConnection(conexion))
                {
                    try
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            connection.Open();
                            command.Connection = connection;
                            command.CommandType = System.Data.CommandType.StoredProcedure;

                            command.CommandText = "TEQUILASO.sp_agregarRol";
                            command.Parameters.AddWithValue("@Id_usuario", id);
                            command.Parameters.AddWithValue("@Id_rol", Convert.ToInt32(rolesGeneralesList.SelectedValue));

                            command.ExecuteReader();
                            connection.Close();
                            MessageBox.Show("Se agregó un nuevo rol.");
                            cargarComboRolesAsignados();
                            cargarComboRolesGenerales();

                            if (rolesGeneralesList.Items.Count == 0)
                            {
                                button1.Enabled = false;
                            }
                            else if (rolesAsignadosList.Items.Count == 0)
                            {
                                button2.Enabled = false;
                            }
                            else
                            {
                                button1.Enabled = true;
                                button2.Enabled = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error al generar el alta.");
                    }
                }
            }
            else
            {
                MessageBox.Show("No hay mas Roles para asignar");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Eliminar Rol
            if (rolesAsignadosList.Text.Length > 0)
            {
                using (SqlConnection connection = new SqlConnection(conexion))
                {
                    try
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            connection.Open();
                            command.Connection = connection;
                            command.CommandType = System.Data.CommandType.StoredProcedure;

                            command.CommandText = "TEQUILASO.sp_eliminarRol";
                            command.Parameters.AddWithValue("@Id_usuario", id);
                            command.Parameters.AddWithValue("@Id_rol", Convert.ToInt32(rolesAsignadosList.SelectedValue));

                            command.ExecuteReader();
                            connection.Close();
                            MessageBox.Show("Se elimino un rol.");
                            cargarComboRolesAsignados();
                            cargarComboRolesGenerales();

                            if (rolesAsignadosList.Items.Count == 0)
                            {
                                button2.Enabled = false;
                            }
                            else if (rolesGeneralesList.Items.Count == 0)
                            {
                                button1.Enabled = false;
                            }
                            else
                            {
                                button1.Enabled = true;
                                button2.Enabled = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error al generar la baja.");
                    }
                }
            }
            else
            {
                MessageBox.Show("No hay mas Roles para eliminar");
            }
            
        }


    } 
}
